<?php
// +----------------------------------------------------------------------
// | 中联致远服务端框架
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.zhongliansoft.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: tony <tanyu@zhongliansoft.com>
// +----------------------------------------------------------------------

namespace app\common\model;
use app\common\model\Config as ConfigsModel;
use app\common\model\BookApply as BookApplyModel;
use app\common\model\BookBatchDraw as BookBatchDrawModel;
use app\common\model\BookPlan as BookPlanModel;
use think\Validate;
use think\Db;
use think\facade\Log;

class BookSupplyDraw extends Common
{
    //时间自动存储
    protected $autoWriteTimestamp = true;
    protected $updateTime = 'time';

    /**
     * @param $post
     *
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function tableData($post)
    {
        if(isset($post['limit'])){
            $limit = $post['limit'];
        }else{
            $limit = config('paginate.list_rows');
        }

        $tableWhere = $this->tableWhere($post);
        
        $list = $this->field('bsd.*, vs.season_name as season, vd.bmmc as dep, vsp.zymc as specialty, vc.plan_class_name as class, vdr.name as dir')
            ->alias('bsd')
            ->leftjoin('zl_view_get_seasons vs', 'vs.season_id = bsd.season')
            ->leftjoin('zl_view_get_depts vd', 'vd.bmdm = bsd.dep_id')
            ->leftjoin('zl_view_get_specicalties vsp', 'vsp.zydm = bsd.specialty_id and vsp.bmdm = bsd.dep_id ')
            ->leftjoin('zl_view_get_classes vc', 'vc.plan_class_id = bsd.class_id and vc.bmdm = bsd.dep_id and vc.zydm = bsd.specialty_id ')
            ->leftjoin('zl_view_get_dirs vdr', 'vdr.id = bsd.dir')
            ->where($tableWhere['where'])
            ->order($tableWhere['order'])
            ->paginate($limit);
        $data = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型

        $re['code'] = 0;
        $re['msg'] = '';
        $re['count'] = $list->total();
        $re['data'] = $data;
        return $re;
    }

    /**
     * 批量插入
     * @param $post
     * @return array
     */
    public function supplydrawsave($post)
    {
        $result = [
            'status' => false,
            'msg'    => '发放失败',
            'data'   => [],
        ];

        // 变量 
        $year = $post['year'];
        $season = $post['season'];
        $dep_id = $post['dep_id'];
        $plan_grade = $post['plan_grade'];
        $plan_degree_id = $post['plan_degree_id'];
        $specialty_id = $post['specialty_id'];
        $class_id = $post['class_id'];
        $dir = $post['dir'];
        $operid = session('manage')['id'];
 
        // 获取教材计划
        $bookPlanModel = new BookPlanModel();
        $wherePlan = []; 
        $wherePlan[] = ['plan_year', 'eq', $year];
        $wherePlan[] = ['plan_season', 'eq', $season];
        $wherePlan[] = ['plan_dep_id', 'eq', $dep_id];
        $wherePlan[] = ['plan_grade', 'eq', $plan_grade];
        $wherePlan[] = ['plan_degree_id', 'eq', $plan_degree_id];

        if($post['specialty_id'] && $post['specialty_id'] != ""){
            $wherePlan[] = ['plan_specialty_id', 'eq', $post['specialty_id']];
        }
        if($post['class_id'] && $post['class_id'] != ""){
            $wherePlan[] = ['plan_code', 'eq', $post['class_id']];
        }
        if($post['dir'] && $post['dir'] != ""){
            $wherePlan[] = ['plan_dir', 'eq', $post['dir']];
        }
        $planInfo = $bookPlanModel->where($wherePlan)->select();
        if($planInfo->isEmpty()){
            $result['msg']    = '发放失败，没有查询到教材计划！';
            return $result;
        }

        $applyInfo2 = $bookPlanModel->field('plan_class_name')
            ->distinct(true)
            ->alias('plan')
            ->join('zl_book_apply apply', 'plan.plan_code = apply.class_id and apply.is_ff = 0')
            ->where($wherePlan)
            ->select();
        
        if(!$applyInfo2->isEmpty()){
            $errNum = 0;
            $result['msg']    = '发放失败:';
            foreach($applyInfo2 as $val) {
                $result['msg'] .= $val['plan_class_name'];
                $errNum++;
                if($errNum > 3) {
                    break;
                }
            }
  
            if($errNum == 1) {
                $result['msg'] .= '已申请发书但尚未发放！';
            } else { 
                $result['msg'] .= '等班级已申请发书但尚未发放！';
            }
            return $result;
        }

        $applyInfo = $bookPlanModel->field('plan_class_name')
            ->distinct(true)
            ->alias('plan')
            ->leftjoin('zl_book_apply apply', 'plan.plan_code = apply.class_id and apply.is_ff = 1')
            ->where($wherePlan)
            ->whereNull('apply.class_id')
            ->select();
        
        $batchInfo = $bookPlanModel->field('plan_class_name')
            ->distinct(true)
            ->alias('plan')
            ->leftjoin('zl_book_batch_draw bd', 'plan.plan_code = bd.class_id')
            ->where($wherePlan)
            ->whereNull('bd.class_id')
            ->select();
        
        if(!$applyInfo->isEmpty() && !$batchInfo->isEmpty()){
            $errNum = 0;
            $result['msg']    = '发放失败:';
            foreach($applyInfo as $val) {
                $result['msg'] .= $val['plan_class_name'];
                $errNum++;
                if($errNum > 3) {
                    break;
                }
            }

            if($result['msg'] === '发放失败:') {
                foreach($batchInfo as $val) {
                    $result['msg'] .= $val['plan_class_name'];
                    $errNum++;
                    if($errNum > 3) {
                        break;
                    }
                }
            }

            if($errNum == 1) {
                $result['msg'] .= '尚未发书！';
            } else { 
                $result['msg'] .= '等班级尚未发书！';
            }
            \think\facade\Request::token('__ZlServer_Token__', 'sha1');
            return $result;
        }
   
        // 图书重复检查
        $model = new Common();
        $checkList = $model->query("call programCheckBookSupplyDraw('".$year."','".$season."','".$dep_id."','".$plan_grade."','".$plan_degree_id."','".$specialty_id."','".$class_id."','".$dir."','".$operid."');");
        
        if(count($checkList) > 0) {
            $result['msg'] = '发放失败:'; 
            foreach($checkList[0] as $val) { 
                $result['msg'] .= $val['plan_class_name'] . ',';
            } 
            
            if (substr($result['msg'], strlen($result['msg'])-1, 1) == ',') {
                $result['msg'] = substr($result['msg'], 0, strlen($result['msg'])-1);
            } 
            
            $result['msg'] .= '已存在该教材';
            return $result;
        }

        // 补发
        $model = new Common();
        $list = $model->query("call programBookSupplyDraw('".$year."','".$season."','".$dep_id."','".$plan_grade."','".$plan_degree_id."','".$specialty_id."','".$class_id."','".$dir."','".$operid."');");
        
        # 发放成功
        $result['status'] = true;
        $result['msg']    = '发放成功';
        return $result;
    }

    // where搜索条件（发放）
    protected function tableWhere($post)
    {
        $where = [];
        if(isset($post['supply_index_year']) && $post['supply_index_year'] != ""){
            $where[] = ['year', 'eq', $post['supply_index_year']];
        }
        if(isset($post['supply_index_season']) && $post['supply_index_season'] != ""){
            $where[] = ['season', 'eq', $post['supply_index_season']];
        }
        if(isset($post['dep_id']) && $post['dep_id'] != ""){
            $where[] = ['dep_id', 'eq', $post['dep_id']];
        }
        if(isset($post['specialty_id']) && $post['specialty_id'] != ""){
            $where[] = ['specialty_id', 'eq', $post['specialty_id']];
        }
        if(isset($post['class_id']) && $post['class_id'] != ""){
            $where[] = ['class_id', 'eq', $post['class_id']];
        }
        if(isset($post['dir']) && $post['dir'] != ""){
            $where[] = ['dir', 'eq', $post['dir']];
        }
        if(isset($post['is_dy']) && $post['is_dy'] != ""){
            $where[] = ['is_dy', 'eq', $post['is_dy']];
        }
        
        $where[] = ["num", "gt", 0];  # 数量为正数
        $result['where'] = $where;
        $result['field'] = "*";
        $result['order'] = ['bsd.year', 'bsd.season', 'bsd.dep_id', 'bsd.specialty_id', 'bsd.class_id', 'bsd.dir', 'bsd.id ASC'];
        return $result;
    }

 
    /**
     * @param $list
     *
     * @return mixed
     */
    public function tableFormat($list)
    {
        foreach($list as &$val){
            $val['time'] = getTime($val['time']); 
            // $val['season'] = getSeason($val['season']);
            // $val['dir'] = getDir($val['dir']);
        }
        return $list;
    }
 
    // 教材补发：重置打印状态 1->0
    public function booksupplyresetprintstatus($data)
    {
        $result = [
            'status' => false,
            'msg'    => '重置失败',
            'data'   => [],
        ];

        $ids_arr = explode(",", $data['ids']);
        $dataList = [];
        foreach($ids_arr as $val) {
            $dataList[] = array('id'=>$val, "is_dy"=>"0");
        }
        # 重置成功
        if($this->isUpdate(true)->saveAll($dataList))
        {
            $result['status'] = true;
            $result['msg']    = '重置成功';
        }
        return $result;
    }

       
    // 教材补发：打印状态改变 0->1
    public function booksupplyprintstatus($data)
    {
        $result = [
            'status' => false,
            'msg'    => '打印失败',
            'data'   => [],
        ];

        $ids_arr = explode(",", $data['ids']);
        $dataList = [];
        foreach($ids_arr as $val) {
            $dataList[] = array('id'=>$val, "is_dy"=>"1");
        }
        # 打印成功
        if($this->isUpdate(true)->saveAll($dataList))
        {
            $result['status'] = true;
            $result['msg']    = '打印成功';
        }
        return $result;
    }
}